#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "cairo-rendering.h"

cairo_t * create_cairo_context(int width, int height, int channels,
										 cairo_surface_t **surf, unsigned char **buffer)
{
	cairo_t *cr;

	// create cairo-surface/context to act as OpenGL-texture source
	*buffer = calloc(channels * width * height, sizeof(unsigned char));
	if (!*buffer)
	{
		printf("create_cairo_context() - Couldn't allocate buffer\n");
		return NULL;
	}

	*surf = cairo_image_surface_create_for_data(*buffer, CAIRO_FORMAT_ARGB32, 
						width, height, channels * width);
	if (cairo_surface_status(*surf) != CAIRO_STATUS_SUCCESS)
	{
		free(*buffer);
		printf("create_cairo_context() - Couldn't create surface\n");
		return NULL;
	}

	cr = cairo_create(*surf);
	if (cairo_status(cr) != CAIRO_STATUS_SUCCESS)
	{
		free(*buffer);
		printf("create_cairo_context() - Couldn't create context\n");
		return NULL;
	}

	return cr;
}

void render_curve(cairo_t *cr, int width, int height)
{

	static int L = 0;
	if( L++ > width/2 )
	{
		L = 0;
	}

	cairo_save (cr);

	// clear background
	cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
	cairo_scale (cr, (double)1.0, (double)1.0);
	cairo_set_source_rgba (cr, 0.0f, 0.0f, 0.25f, 1.0f);
	cairo_paint (cr);

	/*线宽为 9pt 为参数*/
	cairo_set_line_width (cr, L);

	cairo_set_source_rgb (cr, 0.7, 1.0, 0);
	cairo_arc (cr, width / 2, height / 2, L, 0, 2 * M_PI);

	/* cairo_stroke_preserve() :  函数会将它绘制的路径依然保存在 cairo 环境中，*/
	/* cairo_stroke() : 所绘制的路径，在绘制完成后，就从 cairo的环境中清除了。 */
	cairo_stroke_preserve (cr);

	cairo_set_source_rgb (cr, 0.3, 0.4, 0.6);
	cairo_fill (cr);

	cairo_restore (cr);
}
